package com.mango.jdbctemplate.service;

import com.mango.jdbctemplate.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.RowMapperResultSetExtractor;
import org.springframework.stereotype.Service;
import org.springframework.validation.BeanPropertyBindingResult;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 描述:
 * 用户实现类
 *
 * @author 凌风的MI
 * @create 2020-05-20 22:09
 */
@Service
public class UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public Integer addUser(User user){
        return jdbcTemplate.update("insert into user (username,address) values (?,?)", user.getUsername(), user.getAddress());
    }

    public Integer updateUser(User user){
        return jdbcTemplate.update("update user set username=? where id=?", user.getUsername(), user.getId());
    }

    public Integer deleteUserById(Integer id){
        return jdbcTemplate.update("delete from user where id=?",id);
    }

    public List<User> getAllUser(){
        return jdbcTemplate.query("select id,username,address from user", new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setUsername(resultSet.getString(2));
                user.setAddress(resultSet.getString(3));
                return user;
            }
        });
    }

    public List<User> queryAllUser(){
        return jdbcTemplate.query("select id,username,address from user",new BeanPropertyRowMapper<>(User.class));
    }
}
